package org.rcy.ruicingmarket.address;

import org.rcy.framework.api.distributed.DistributedTransaction;
import org.rcy.framework.api.distributed.DistributedTransactional;
import org.rcy.ruicingmarket.common.utils.CollectionBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * @author RuicyWu
 * @Date 2022/3/11 8:56
 */
@Service
public class AddressService {
    @Autowired
    private AddressDao addressDao;

    /**
     * 新增地址
     * @param vo
     */
    @Transactional
    public void create(AddressVo vo){
        Address address = new Address();
        BeanUtils.copyProperties(vo,address);
        addressDao.insertSelective(address);
    }

    /**
     * 查询用户的收货地址列表
     * @param uid
     * @return
     */
    public List<AddressVo> queryAddressListByUid(Long uid){
        return CollectionBeanUtils.copyListProperties(addressDao.queryListByUid(uid),AddressVo::new);
    }

    /**
     * 修改地址
     */
    @Transactional
    public void editAddress(AddressVo vo){
        Address address = addressDao.get(vo.getId());
        BeanUtils.copyProperties(vo,address);
        address.setCreateTime(null);
        addressDao.update(address,true);
    }

    /**
     * 删除地址
     * @param id
     */
    @Transactional
    public void delAddress(Long id){
        addressDao.delete(id);
    }
    /**
     * 统计用户收货地址数量
     * @param uid
     * @return
     */
    public int countAddress(Long uid){
        return addressDao.countAddressByUid(uid);
    }

    public AddressVo getById(Long id){
        Address address = addressDao.get(id);
        AddressVo vo = new AddressVo();
        BeanUtils.copyProperties(address,vo);
        return vo;
    }


    public DistributedTransaction testDisT(AddressVo vo,DistributedTransaction transaction){
        try {
            Address address = new Address();
            address.setAddr("但都花园");
            address.setUid(546545646L);
            addressDao.insertSelective(address);
        }catch (Exception e){
            System.out.println(e.getMessage());
            transaction.setException(e);
            transaction.setRollback(true);
        }
        return transaction;
    }
}
